/*
 * Copyright 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.android.navigationdrawerexample;
import java.util.ArrayList;
import java.util.List;

import android.R.style;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.text.Editable;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.google.ads.Ad;
import com.google.ads.AdListener;
import com.google.ads.AdRequest;
import com.google.ads.AdRequest.ErrorCode;
import com.google.ads.AdSize;
import com.google.ads.AdView;
import com.phonebrand.adater.AdapterTelListViewData;
import com.phonebrand.adater.PackageAdapterView;
import com.phonebrand.constant.PhoneBrandConstant;
import com.phonebrand.dao.DB4CommandDao;
import com.phonebrand.global.GlobalApplication;
import com.phonebrand.model.PackageM;
import com.phonebrand.model.PhoneM;
import com.phonebrand.service.PhoneService;
/*import android.app.Fragment;
import android.app.FragmentManager;*/

/**
 * This example illustrates a common usage of the DrawerLayout widget in the
 * Android support library.
 * <p/>
 * <p>
 * When a navigation (left) drawer is present, the host activity should detect
 * presses of the action bar's Up affordance as a signal to open and close the
 * navigation drawer. The ActionBarDrawerToggle facilitates this behavior. Items
 * within the drawer should fall into one of two categories:
 * </p>
 * <p/>
 * <ul>
 * <li><strong>View switches</strong>. A view switch follows the same basic
 * policies as list or tab navigation in that a view switch does not create
 * navigation history. This pattern should only be used at the root activity of
 * a task, leaving some form of Up navigation active for activities further down
 * the navigation hierarchy.</li>
 * <li><strong>Selective Up</strong>. The drawer allows the user to choose an
 * alternate parent for Up navigation. This allows a user to jump across an
 * app's navigation hierarchy at will. The application should treat this as it
 * treats Up navigation from a different task, replacing the current task stack
 * using TaskStackBuilder or similar. This is the only form of navigation drawer
 * that should be used outside of the root activity of a task.</li>
 * </ul>
 * <p/>
 * <p>
 * Right side drawers should be used for actions, not navigation. This follows
 * the pattern established by the Action Bar that navigation should be to the
 * left and actions to the right. An action should be an operation performed on
 * the current contents of the window, for example enabling or disabling a data
 * overlay on top of the current content.
 * </p>
 */
//public class MainActivity extends Activity {
	public class MainActivity extends FragmentActivity{
	private static final String LOG_TAG = "MainActivity";
	
	private DB4CommandDao dao; 
	private DrawerLayout mDrawerLayout;
	private ListView mDrawerList;
	private ActionBarDrawerToggle mDrawerToggle;

//	private CharSequence mDrawerTitle;
//	private CharSequence mTitle;
	private String[] mPlanetTitles;
    private int positionG;
    private int positionCurrent;
	private int  child_size;
	private boolean isOpen;
	private static ListView listV;    
	private static EditText numberEdit;
	private static EditText searchNum;
	private static TextView showBrand;
	    
	private static LinearLayout callButton;   
	private static LinearLayout showNumLayOut;  
	private static View rootView ;
	private static AdView adView;
	
	private static Button oneBt;
	private static Button twoBt;
	private static Button threeBt;
	private static Button fourBt;
	private static Button fiveBt;
	private static Button sixBt;
	private static Button sevenBt;
	private static Button eightBt;
	private static Button nineBt;
	private static Button zeroBt;
	private static Button sin1Bt;
	private static Button sin2Bt;

	private static Button callPhoneBt;
	private static Button delBt;
	
	private static boolean isLoad;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
	
		setContentView(R.layout.activity_main);  
		setTheme(style.Theme_Holo_Light);  
		super.onCreate(savedInstanceState); 
		if (android.os.Build.VERSION.SDK_INT > 9) {
		    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		    StrictMode.setThreadPolicy(policy);
		}
		 
		dao = DB4CommandDao.getInstance();
	   
	   
	//	mTitle = mDrawerTitle = getTitle(); 
	//	mTitle = getTitle();
		mPlanetTitles = getResources().getStringArray(R.array.planets_array);
		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		mDrawerList = (ListView) findViewById(R.id.left_drawer); 
		// set a custom shadow that overlays the main content when the drawer
		// opens
		mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
				GravityCompat.START);
		// set up the drawer's list view with items and click listener  
		mDrawerList.setAdapter(new ArrayAdapter<String>(this,
				R.layout.drawer_list_item, mPlanetTitles)); 
		mDrawerList.setOnItemClickListener(new DrawerItemClickListener()); 
		 
		// enable ActionBar app icon to behave as action to toggle nav drawer
		 ActionBar actionBar = getActionBar();
		    actionBar.setTitle("");  
			actionBar.setDisplayHomeAsUpEnabled(true);
			actionBar.setHomeButtonEnabled(true);  
			actionBar.setDisplayShowTitleEnabled(false);
		// ActionBarDrawerToggle ties together the the proper interactions
		// between the sliding drawer and the action bar app icon
		mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
		mDrawerLayout, /* DrawerLayout object */
		R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
		R.string.drawer_open, /* "open drawer" description for accessibility */
		R.string.drawer_close /* "close drawer" description for accessibility */
		) {
			public void onDrawerClosed(View view) {
				// getActionBar().setTitle(mTitle+" mTittle");
				Log.d(LOG_TAG,"onDrawerClosed");
				//getActionBar().setTitle(mTitle);
				invalidateOptionsMenu(); // creates call to
											// onPrepareOptionsMenu()
				android.support.v4.app.Fragment fragment = new PlanetFragment();
		        Bundle args = new Bundle();
		        args.putInt(PlanetFragment.ARG_PLANET_NUMBER, positionG);
		        fragment.setArguments(args);

		       FragmentManager fragmentManager = getSupportFragmentManager();
		       fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
			}

			public void onDrawerOpened(View drawerView) {
				// getActionBar().setTitle(mDrawerTitle+" mDrawerTitle");
				if(!isOpen){ 
					((TextView)((ListView)drawerView).getChildAt(0)).setTextColor(Color.WHITE);
					isOpen=true;
				}
				//getActionBar().setTitle(mTitle);
				invalidateOptionsMenu(); // creates call to
											// onPrepareOptionsMenu()
			}
		};
		mDrawerLayout.setDrawerListener(mDrawerToggle);

		// get All view
		/*showBrand = (TextView)findViewById(R.id.view_brand);
    	
    	numberEdit = (EditText)findViewById(R.id.edit_num);
    	callButton = (LinearLayout)findViewById(R.id.callButton);
    	listV = (ListView)findViewById(R.id.list_result);        	             
    	searchNum = (EditText)findViewById(R.id.search_num);
    	showNumLayOut = (LinearLayout)findViewById(R.id.showEditNum);
    	
    	listV.setVisibility(View.GONE);
		showNumLayOut.setVisibility(View.GONE);
    	showBrand.setVisibility(View.GONE);
		numberEdit.setInputType(InputType.TYPE_NULL);
		callButton.setVisibility(View.GONE);
		searchNum.setVisibility(View.GONE);*/
		 // Create an ad.
		 adView = new AdView(this, AdSize.BANNER, "a1518ba85c35b0d");
		if (savedInstanceState == null) {
			Log.d(LOG_TAG,"savedInstanceState");
			selectItem(0);
			android.support.v4.app.Fragment fragment = new PlanetFragment();
	        Bundle args = new Bundle();
	        args.putInt(PlanetFragment.ARG_PLANET_NUMBER, positionG);
	        fragment.setArguments(args);

	       FragmentManager fragmentManager = getSupportFragmentManager();
	       fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit(); 
		}
	}

	/*
	 * @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater
	 * inflater = getMenuInflater(); inflater.inflate(R.menu.main, menu); return
	 * super.onCreateOptionsMenu(menu); }
	 */

	/* Called whenever we call invalidateOptionsMenu() */
	/*
	 * @Override public boolean onPrepareOptionsMenu(Menu menu) { // If the nav
	 * drawer is open, hide action items related to the content view boolean
	 * drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
	 * menu.findItem(R.id.action_websearch).setVisible(!drawerOpen); return
	 * super.onPrepareOptionsMenu(menu); }
	 */
	  @Override
	    public boolean onCreateOptionsMenu(Menu menu) {
	        MenuInflater inflater = getMenuInflater();
	        inflater.inflate(R.menu.main, menu);
	        return super.onCreateOptionsMenu(menu);
	    } 
   
	/* @Override
	public boolean onContextItemSelected(MenuItem item) {
	    Log.d(LOG_TAG,"onContextItemSelected->"+item.getItemId());
		// TODO Auto-generated method stub
		return super.onContextItemSelected(item);
	}*/

		/* Called whenever we call invalidateOptionsMenu() */
	    @Override
	    public boolean onPrepareOptionsMenu(Menu menu) {
	        // If the nav drawer is open, hide action items related to the content view
	      //  boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
	      //  menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
	    	 /* menu.findItem(R.id.keypad_icon).setVisible(true);
	    	  menu.findItem(R.id.calllog_icon).setVisible(true);
	    	  menu.findItem(R.id.favorite_icon).setVisible(true);
	    	  menu.findItem(R.id.phonbook_icon).setVisible(true); */
	        return super.onPrepareOptionsMenu(menu);
	    }

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// The action bar home/up action should open or close the drawer.
		// ActionBarDrawerToggle will take care of this.
		Log.d(LOG_TAG,"getItemId->"+item.getItemId());
		Log.d(LOG_TAG,"mDrawerToggle->"+mDrawerToggle.onOptionsItemSelected(item));
		if (mDrawerToggle.onOptionsItemSelected(item)) {
			return true;
		}
		// Handle action buttons
		switch (item.getItemId()) {
		case R.id.keypad_icon:
			return true;
		case R.id.calllog_icon:
			return true;
		case R.id.favorite_icon:
			return true;
		case R.id.phonbook_icon:
			return true;
		/*
		 * case R.id.action_websearch: // create intent to perform web search
		 * for this planet Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
		 * intent.putExtra(SearchManager.QUERY, getActionBar().getTitle()); //
		 * catch event that there's no activity to handle intent if
		 * (intent.resolveActivity(getPackageManager()) != null) {
		 * startActivity(intent); } else { Toast.makeText(this,
		 * R.string.app_not_available, Toast.LENGTH_LONG).show(); } return true;
		 */
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	/* The click listner for ListView in the navigation drawer */
	private class DrawerItemClickListener implements
			ListView.OnItemClickListener {

		/*
		 * @Override public void onItemClick(AdapterView<?> arg0, View arg1, int
		 * arg2, long arg3) { // TODO Auto-generated method stub
		 * 
		 * }
		 */
		
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			 //reset color
			child_size=mDrawerList.getChildCount();
			Log.d(LOG_TAG,child_size+"");
			for (int i = 0; i < child_size; i++) {
				TextView child=(TextView)mDrawerList.getChildAt(i);
				child.setTextColor(Color.parseColor("#5B5B5B"));
			} 
			TextView currentText=(TextView)view;
			currentText.setTextColor(Color.WHITE); 
			// end
			selectItem(position);
		}

	}

	private void selectItem(int position) { 

		// update selected item and title, then close the drawer
		positionG=position;
		mDrawerList.setItemChecked(position, true);
		  
		//setTitle(mPlanetTitles[position]);
		mDrawerLayout.clearAnimation(); 
		Log.d(LOG_TAG, position+"");  
		mDrawerLayout.closeDrawer(mDrawerList); 
		
		//getTitle().setTextColor();
		// update the main content by replacing fragments
		/*Fragment fragment = new PlanetFragment();
				Bundle args = new Bundle();
				args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
				fragment.setArguments(args);

				FragmentManager fragmentManager = getFragmentManager();
				fragmentManager.beginTransaction()
						.replace(R.id.content_frame, fragment).commit();*/
		//aoe add
				/*android.support.v4.app.Fragment fragment = new PlanetFragment();
		        Bundle args = new Bundle();
		        args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
		        fragment.setArguments(args);

		       FragmentManager fragmentManager = getSupportFragmentManager();
		       fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();*/
	}
	
	@Override
	public void setTitle(CharSequence title) {
	//	mTitle = title;
		//getActionBar().setTitle(mTitle);
	}

	/**
	 * When using the ActionBarDrawerToggle, you must call it during
	 * onPostCreate() and onConfigurationChanged()...
	 */

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		// Sync the toggle state after onRestoreInstanceState has occurred.
		mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// Pass any configuration change to the drawer toggls
		mDrawerToggle.onConfigurationChanged(newConfig);
	}
	 /**
     * Fragment that appears in the "content_frame", shows a planet
     */
   /* public static class PlanetFragment extends android.support.v4.app.Fragment {
        public static final String ARG_PLANET_NUMBER = "planet_number";

        public PlanetFragment() {
            // Empty constructor required for fragment subclasses
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_planet, container, false);
            int i = getArguments().getInt(ARG_PLANET_NUMBER);

            return rootView;
        }
    }*/
	/**
	 * Fragment that appears in the "content_frame", shows a planet
	 */
	//public static class PlanetFragment extends Fragment {
   //public static class PlanetFragment extends android.support.v4.app.Fragment implements AdListener {
	@SuppressLint("ValidFragment")
	public  class PlanetFragment extends android.support.v4.app.Fragment implements AdListener{
	//, LoaderManager.LoaderCallbacks<Cursor> {
		  
	// public static class PlanetFragment extends android.support.v4.app.FragmentActivity implements AdListener {
		public static final String ARG_PLANET_NUMBER = "planet_number";
		private ProgressDialog progressDialog = null;
		public  PlanetFragment() {
			// Empty constructor required for fragment subclasses
			Log.d(LOG_TAG,"into new PlanetFragment is load->"+isLoad);
			                                         // Default sort order
		}

		@Override
		public void setRetainInstance(boolean retain) {
			// TODO Auto-generated method stub
			super.setRetainInstance(retain);
		}

		@Override
		public void onStop() {
			// TODO Auto-generated method stub
			if(progressDialog!=null && progressDialog.isShowing())
        		progressDialog.dismiss();
			super.onStop();
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			Log.d(LOG_TAG,"into onCreateView is load->"+isLoad+","+getActivity());
		                                          // Default sort order
			int i = getArguments().getInt(ARG_PLANET_NUMBER);
			boolean sameView=true;
			if(i!=positionCurrent){
			  sameView=false;
			  positionCurrent=i;
			 if(i==1 || i==2 || i==3 ){
					progressDialog = new ProgressDialog(getActivity());
					progressDialog.setTitle(null);
	            	progressDialog.setMessage("Please wait...");
	           // 	progressDialog.setIndeterminate(true);
	            //	progressDialog.setCancelable(false);
	            	if(progressDialog!=null && !progressDialog.isShowing())
	            		progressDialog.show();
					/*new Thread(new Runnable() {
		    		    public void run() { 
		    		    	getActivity().runOnUiThread(new Runnable() { 
		    		            public void run() {
		    		            	progressDialog.setTitle(null);
		    		            	progressDialog.setMessage("Please wait...");
		    		           // 	progressDialog.setIndeterminate(true);
		    		            //	progressDialog.setCancelable(false);
		    		            	if(progressDialog!=null && !progressDialog.isShowing())
		    		            		progressDialog.show();
		    		            }
		    		        }); 
		    		    } 
		    		}).start();  */
			 }
		}
			// if(rootView==null){
				 rootView = inflater.inflate(R.layout.mainphone,
					container, false);
			 //}
			//int i = getArguments().getInt(ARG_PLANET_NUMBER);
			  //getLoaderManager().initLoader(0, null, this);
		//	if(!isLoad){
				isLoad=true;
				
				Log.d(LOG_TAG,i+"");
			//	 adView = new AdView(this, AdSize.BANNER, "a1518ba85c35b0d"); 	
	         	 LinearLayout layout = (LinearLayout)rootView.findViewById(R.id.adLayOut);
	         	
	         	 if(adView.getParent()!=null)
	         		 ((LinearLayout)adView.getParent()).removeView(adView);
	            layout.addView(adView);

	        	// Initiate a generic request to load it with an ad
	        	adView.loadAd(new AdRequest());
				
			
			    // Set the AdListener.
			   // adView.setAdListener(this); 
			    showNumLayOut = (LinearLayout)rootView.findViewById(R.id.showEditNum); 
				showBrand = (TextView)rootView.findViewById(R.id.view_brand);
				numberEdit = (EditText)rootView.findViewById(R.id.edit_num);
		    	callButton = (LinearLayout)rootView.findViewById(R.id.callButton); 	    	       	             
		    	searchNum = (EditText)rootView.findViewById(R.id.search_num);
		    	listV = (ListView)rootView.findViewById(R.id.list_result); 
		    	
				 oneBt = (Button)rootView.findViewById(R.id.oneBt);
		            twoBt =(Button)rootView.findViewById(R.id.twoBt);
		            threeBt = (Button)rootView.findViewById(R.id.threeBt);
		            fourBt = (Button)rootView.findViewById(R.id.fourBt);
		            fiveBt = (Button)rootView.findViewById(R.id.fiveBt);
		            sixBt = (Button)rootView.findViewById(R.id.sixBt);
		            sevenBt = (Button)rootView.findViewById(R.id.sevenBt);
		            eightBt = (Button)rootView.findViewById(R.id.eightBt);
		            nineBt = (Button)rootView.findViewById(R.id.nineBt);
		            zeroBt =(Button)rootView.findViewById(R.id.zeroBt);
		            sin1Bt =(Button)rootView.findViewById(R.id.syn1Bt);
		            sin2Bt =(Button)rootView.findViewById(R.id.syn2Bt);
		            callPhoneBt =(Button)rootView.findViewById(R.id.callPhoneBt);
		            delBt =(Button)rootView.findViewById(R.id.RemoveBt);
		        	
		        	oneBt.setOnClickListener(new OnClickListener() {								
						public void onClick(View v) {
							// TODO Auto-generated method stub
							numberEdit.setText(numberEdit.getText()+"1");
							showBrand();
						}
					});
		        	
		        	twoBt.setOnClickListener(new OnClickListener() {								
						public void onClick(View v) {
							// TODO Auto-generated method stub
							numberEdit.setText(numberEdit.getText()+"2");
							showBrand();
						}
					});
		        	        	
		        	threeBt.setOnClickListener(new OnClickListener() {								
						public void onClick(View v) {
							// TODO Auto-generated method stub
							numberEdit.setText(numberEdit.getText()+"3");
							showBrand();
						}
					});
		        	
		        	fourBt.setOnClickListener(new OnClickListener() {								
						public void onClick(View v) {
							// TODO Auto-generated method stub
							numberEdit.setText(numberEdit.getText()+"4");
							showBrand();
						}
					});
		        	
		        	fiveBt.setOnClickListener(new OnClickListener() {								
						public void onClick(View v) {
							// TODO Auto-generated method stub
							numberEdit.setText(numberEdit.getText()+"5");
							showBrand();
						}
					});
		        	
		        	sixBt.setOnClickListener(new OnClickListener() {								
						public void onClick(View v) {
							// TODO Auto-generated method stub
							numberEdit.setText(numberEdit.getText()+"6");
							showBrand();
						}
					});
		        	
		        	sevenBt.setOnClickListener(new OnClickListener() {								
						public void onClick(View v) {
							// TODO Auto-generated method stub
							numberEdit.setText(numberEdit.getText()+"7");
							showBrand();
						}
					});
		        	
		        	eightBt.setOnClickListener(new OnClickListener() {								
						public void onClick(View v) {
							// TODO Auto-generated method stub
							numberEdit.setText(numberEdit.getText()+"8");
							showBrand();
						}
					});
		        	
		        	nineBt.setOnClickListener(new OnClickListener() {								
						public void onClick(View v) {
							// TODO Auto-generated method stub
							numberEdit.setText(numberEdit.getText()+"9");
							showBrand();
						}
					});
		        	
		        	zeroBt.setOnClickListener(new OnClickListener() {								
						public void onClick(View v) {
							// TODO Auto-generated method stub
							numberEdit.setText(numberEdit.getText()+"0");
							showBrand();
						}
					});
		        	
		        	sin1Bt.setOnClickListener(new OnClickListener() {								
						public void onClick(View v) {
							// TODO Auto-generated method stub
							numberEdit.setText(numberEdit.getText()+"*");
							showBrand();
						}
					});
		        	
		        	sin2Bt.setOnClickListener(new OnClickListener() {								
						public void onClick(View v) {
							// TODO Auto-generated method stub
							numberEdit.setText(numberEdit.getText()+"#");
							showBrand();
						}
					});
		        	        	

		        	callPhoneBt.setOnClickListener(new OnClickListener() {								
						public void onClick(View v) {
			            	   try {
								   String telNum = numberEdit.getText().toString();
								   telNum = "tel:"+telNum;
								   Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(telNum));
								   intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
								   startActivity(intent);
							   }catch (Exception e) {
								   e.printStackTrace();
							   }
						}
					});
		        	        	
		        	delBt.setOnClickListener(new OnClickListener() {								
						public void onClick(View v) {
							// TODO Auto-generated method stub
							try {
								if(numberEdit.getText().length()!=0)
									numberEdit.setText(numberEdit.getText().toString().substring(0,numberEdit.getText().toString().length()-1 ));
								showBrand();
							} catch (Exception e) {
								e.printStackTrace();
							}	
						}
					});
		        	searchNum.addTextChangedListener(new android.text.TextWatcher() {
						
						@Override
						public void onTextChanged(CharSequence s, int start, int before, int count) {
							// TODO Auto-generated method stub					
							ArrayList<PhoneM> phoneMs =  filterContract(searchNum.getText().toString());
				        	AdapterTelListViewData adapterListViewData;
					        adapterListViewData = new AdapterTelListViewData(getBaseContext(),phoneMs,PhoneBrandConstant.MODECONTACT);	   	 		        
					        listV.setAdapter(adapterListViewData);
					        listV.invalidate();
						}
						
						@Override
						public void beforeTextChanged(CharSequence s, int start, int count,
								int after) {
							// TODO Auto-generated method stub
							
						}
						
						@Override
						public void afterTextChanged(Editable s) {
							// TODO Auto-generated method stub
							
						}
					}
				); 
		//	}
			/*View rootView = inflater.inflate(R.layout.fragment_planet,
					container, false);
			int i = getArguments().getInt(ARG_PLANET_NUMBER);
			String planet = getResources()
					.getStringArray(R.array.planets_array)[i];

			int imageId = getResources().getIdentifier(
					planet.toLowerCase(Locale.getDefault()), "drawable",
					getActivity().getPackageName());
			((ImageView) rootView.findViewById(R.id.image))
					.setImageResource(imageId);
			getActivity().setTitle(planet);*/
		
	    	
	    	//listV.setVisibility(View.GONE);
	    	if(i==0){
	    		listV.setVisibility(View.GONE);
	    		showNumLayOut.setVisibility(View.VISIBLE);
	    		showBrand.setVisibility(View.VISIBLE);
	    		numberEdit.setInputType(InputType.TYPE_NULL);
	    		callButton.setVisibility(View.VISIBLE);
	    		searchNum.setVisibility(View.GONE);
	    		listV.setVisibility(View.GONE); 
	    	}else if(i==1){
	    		listV.setVisibility(View.VISIBLE);
				showNumLayOut.setVisibility(View.GONE);
	        	showBrand.setVisibility(View.GONE);
				callButton.setVisibility(View.GONE);
				searchNum.setVisibility(View.GONE);
				//refreshLog();			
	    	}else if(i==2){
	    		listV.setVisibility(View.VISIBLE);
				showNumLayOut.setVisibility(View.GONE);
	        	showBrand.setVisibility(View.GONE);
				callButton.setVisibility(View.GONE);
				searchNum.setVisibility(View.GONE);
				//refreshFavorite();
	    	}else if(i==3){
	    		listV.setVisibility(View.VISIBLE);
				showNumLayOut.setVisibility(View.GONE);
	        	showBrand.setVisibility(View.GONE);
				callButton.setVisibility(View.GONE);
				searchNum.setVisibility(View.VISIBLE);
				//refreshContactData();			
	    	}else if(i==4){
	    		listV.setVisibility(View.VISIBLE);
				showNumLayOut.setVisibility(View.GONE);
	        	showBrand.setVisibility(View.GONE);
				callButton.setVisibility(View.GONE);
				searchNum.setVisibility(View.GONE);
	    	}
	    	//progressDialog.dismiss();
      //  if(!sameView){
          if(i!=4){
	        new LoaddataAsync(i,listV,progressDialog)
	                .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new Integer[]{Integer.valueOf(i)}); 
          }else{
	        new LoadPackageAsync(listV,progressDialog)
            .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new Integer[]{Integer.valueOf(i)}); 
          }
      //  }
			return rootView;
		}

		@Override
		public void onDismissScreen(Ad arg0) {
			// TODO Auto-generated method stub
			 if (adView != null) {
			        adView.destroy();
			      }
		}

		@Override
		public void onFailedToReceiveAd(Ad arg0, ErrorCode arg1) {
			// TODO Auto-generated method stub
			 if (adView != null) {
			        adView.destroy();
			      }
		}

		@Override
		public void onLeaveApplication(Ad arg0) {
			// TODO Auto-generated method stub
			 if (adView != null) {
			        adView.destroy();
			      }
		}

		@Override
		public void onPresentScreen(Ad arg0) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onReceiveAd(Ad arg0) {
			// TODO Auto-generated method stub
			
		}


		/*@Override
		public Loader<Cursor> onCreateLoader(int loaderID, Bundle arg1) {
			// TODO Auto-generated method stub
			Log.d(LOG_TAG,"into onCreateLoader");
			 
	         * Takes action based on the ID of the Loader that's being created
	         
	        switch (loaderID) {
	            case 0:
	            // Returns a new CursorLoader
	            	
	            default:
	                // An invalid id was passed in
	                return null;

	        }
		}


		@Override
		public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {
			// TODO Auto-generated method stub
			Log.d(LOG_TAG,"into onLoadFinished");
			//Log.d(LOG_TAG,"into onLoadFinished->"+progressDialog);
			//progressDialog.dismiss();
		}


		@Override
		public void onLoaderReset(Loader<Cursor> arg0) {
			// TODO Auto-generated method stub
			
		}*/


		/*@Override
		public void onDetach() {
			// TODO Auto-generated method stub
			 // Destroys variables and references, and catches Exceptions
	        try {
	            getLoaderManager().destroyLoader(0);
	        } catch (Throwable localThrowable) {
	        }
	        
	        // Always call the super method last
	        super.onDetach();
	        return;
		}*/

		// implement onloader
		/*@Override
		public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
			// TODO Auto-generated method stub
			Log.d(LOG_TAG,"into onCreateLoader");
			return null;
		}

		@Override
		public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {
			// TODO Auto-generated method stub
			Log.d(LOG_TAG,"into onLoadFinished");
		}

		@Override
		public void onLoaderReset(Loader<Cursor> arg0) {
			// TODO Auto-generated method stub
			Log.d(LOG_TAG,"into onLoaderReset");
		}*/
	}
    private static void showBrand() {
    	try {
    		String strPhone = numberEdit.getText().toString();
    		if (strPhone.length() == 10) {
    			String brand = PhoneService.getInstance().getBrand(strPhone.replace("+66", "0"));
    			showBrand.setText(brand);
    		} else {
    			showBrand.setText("");
    		}
    	} catch (Exception e) {
    		e.printStackTrace();
    		showBrand.setText("");
    	}
    	
    }
    public  ArrayList<PhoneM>  refreshLogByAoe() {
    	ArrayList<PhoneM> listLogItems = new ArrayList<PhoneM>();
    	try {    		    	
    		 String[] strFields = {
                     android.provider.CallLog.Calls.DATE,
                     android.provider.CallLog.Calls.NUMBER, 
                     android.provider.CallLog.Calls.TYPE,
                     android.provider.CallLog.Calls.DURATION,
                 //    android.provider.CallLog.Calls.NEW,
                     android.provider.CallLog.Calls.CACHED_NAME,
                //     android.provider.CallLog.Calls.CACHED_NUMBER_TYPE,
                //     android.provider.CallLog.Calls.CACHED_NUMBER_LABEL//,
             };
    		
    		
    	
    		 Cursor c = getApplicationContext().getContentResolver().query(
                     android.provider.CallLog.Calls.CONTENT_URI,
                     strFields,
                     null,
                     null,
                    "date DESC"
                 );	    	
	    	/*
	    	for (String columnName : c.getColumnNames()) {
	    		Log.i("PhoneBrand", " columnName : "+columnName);
	    	}
	    	*/
    		 int i= 0;
    		PhoneM compareM = new PhoneM();	
	    	while (c.moveToNext() && i < 150) {	    		
	    		
    			if (c.getString(c.getColumnIndex(CallLog.Calls.NUMBER)) != null && (c.getString(c.getColumnIndex(CallLog.Calls.NUMBER)).length() >=10) && checkNumber(c.getString(c.getColumnIndex(CallLog.Calls.NUMBER)))    ) {
		    			    			
	    			PhoneM phoneM = new PhoneM();	    			    			    			    			    			    		
		    		phoneM.setPhoneNum(c.getString(c.getColumnIndex(CallLog.Calls.NUMBER)));		    		
		    		phoneM.setName(c.getString(c.getColumnIndex(CallLog.Calls.CACHED_NAME)));		 
		    		phoneM.setType(c.getString(c.getColumnIndex(CallLog.Calls.TYPE)));
		    		phoneM.setCountNUm(1);
		    		PhoneM loadPhone = DB4CommandDao.getInstance().loadPhoneMByNum(phoneM.getPhoneNum(),((GlobalApplication)getApplication()).getDbPhone());
		    		
		    		if (loadPhone != null) {
		    			phoneM.setBrandName(loadPhone.getBrandName());
		    		}else {
		    			if (i < 1) {
		    				Log.d(LOG_TAG,PhoneService.getInstance().getURL());
		    				phoneM.setBrandName(PhoneService.getInstance().getBrand(phoneM.getPhoneNum().replace("+66", "0")));
		    			}
		    		}
		    		
		    		//	phoneM.setBrandName(c.getString(c.getColumnIndex(CallLog.Calls.CONTENT_TYPE)));
		    	
		    //		String duration = c.getString(c.getColumnIndex(CallLog.Calls.DURATION));// for duration
		    //		int type = Integer.parseInt(c.getString(c.getColumnIndex(CallLog.Calls.TYPE)));// for call type, Incoming or out going
		    		if (phoneM.getPhoneNum().equalsIgnoreCase(compareM.getPhoneNum()) && phoneM.getType().equalsIgnoreCase(compareM.getType())) {
		    			 listLogItems.get(listLogItems.size() -1).setCountNUm(listLogItems.get(listLogItems.size() -1).getCountNUm() +1);
		    		} else {
		    			listLogItems.add(phoneM);	
		    		}
		    		i++;
	    			compareM.setPhoneNum(c.getString(c.getColumnIndex(CallLog.Calls.NUMBER)));
	    			compareM.setType(c.getString(c.getColumnIndex(CallLog.Calls.TYPE)));		
    			}
    		
    			
	    	}
	    	//c.close();
	    	//return listLogItems;
        	/*AdapterTelListViewData adapterListViewData;
	        adapterListViewData = new AdapterTelListViewData(getBaseContext(),listLogItems,PhoneBrandConstant.MODELOG);	   	 		        
	        listV.setAdapter(adapterListViewData);
	        listV.invalidate();*/
	    		    		    	
    	
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
		return listLogItems;
    }
   
    public  void refreshLog() {
    	try {    		    	
    		 String[] strFields = {
                     android.provider.CallLog.Calls.DATE,
                     android.provider.CallLog.Calls.NUMBER, 
                     android.provider.CallLog.Calls.TYPE,
                     android.provider.CallLog.Calls.DURATION,
                 //    android.provider.CallLog.Calls.NEW,
                     android.provider.CallLog.Calls.CACHED_NAME,
                //     android.provider.CallLog.Calls.CACHED_NUMBER_TYPE,
                //     android.provider.CallLog.Calls.CACHED_NUMBER_LABEL//,
             };
    		
    		
    		ArrayList<PhoneM> listLogItems = new ArrayList<PhoneM>();
    		 Cursor c = getApplicationContext().getContentResolver().query(
                     android.provider.CallLog.Calls.CONTENT_URI,
                     strFields,
                     null,
                     null,
                    "date DESC"
                 );	    	
	    	/*
	    	for (String columnName : c.getColumnNames()) {
	    		Log.i("PhoneBrand", " columnName : "+columnName);
	    	}
	    	*/
    		 int i= 0;
    		PhoneM compareM = new PhoneM();	
	    	while (c.moveToNext() && i < 150) {	    		
	    		
    			if (c.getString(c.getColumnIndex(CallLog.Calls.NUMBER)) != null && (c.getString(c.getColumnIndex(CallLog.Calls.NUMBER)).length() >=10) && checkNumber(c.getString(c.getColumnIndex(CallLog.Calls.NUMBER)))    ) {
		    			    			
	    			PhoneM phoneM = new PhoneM();	    			    			    			    			    			    		
		    		phoneM.setPhoneNum(c.getString(c.getColumnIndex(CallLog.Calls.NUMBER)));		    		
		    		phoneM.setName(c.getString(c.getColumnIndex(CallLog.Calls.CACHED_NAME)));		 
		    		phoneM.setType(c.getString(c.getColumnIndex(CallLog.Calls.TYPE)));
		    		phoneM.setCountNUm(1);
		    		PhoneM loadPhone = DB4CommandDao.getInstance().loadPhoneMByNum(phoneM.getPhoneNum(),((GlobalApplication)getApplication()).getDbPhone());
		    		
		    		if (loadPhone != null) {
		    			phoneM.setBrandName(loadPhone.getBrandName());
		    		}else {
		    			if (i < 1) {
		    				Log.d(LOG_TAG,PhoneService.getInstance().getURL());
		    				phoneM.setBrandName(PhoneService.getInstance().getBrand(phoneM.getPhoneNum().replace("+66", "0")));
		    			}
		    		}
		    		
		    		//	phoneM.setBrandName(c.getString(c.getColumnIndex(CallLog.Calls.CONTENT_TYPE)));
		    	
		    //		String duration = c.getString(c.getColumnIndex(CallLog.Calls.DURATION));// for duration
		    //		int type = Integer.parseInt(c.getString(c.getColumnIndex(CallLog.Calls.TYPE)));// for call type, Incoming or out going
		    		if (phoneM.getPhoneNum().equalsIgnoreCase(compareM.getPhoneNum()) && phoneM.getType().equalsIgnoreCase(compareM.getType())) {
		    			 listLogItems.get(listLogItems.size() -1).setCountNUm(listLogItems.get(listLogItems.size() -1).getCountNUm() +1);
		    		} else {
		    			listLogItems.add(phoneM);	
		    		}
		    		i++;
	    			compareM.setPhoneNum(c.getString(c.getColumnIndex(CallLog.Calls.NUMBER)));
	    			compareM.setType(c.getString(c.getColumnIndex(CallLog.Calls.TYPE)));		
    			}
    		
    			
	    	}
	    	//c.close();
	    	
        	AdapterTelListViewData adapterListViewData;
	        adapterListViewData = new AdapterTelListViewData(getBaseContext(),listLogItems,PhoneBrandConstant.MODELOG);	   	 		        
	        listV.setAdapter(adapterListViewData);
	        listV.invalidate();
	    		    		    	
    	
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    }
    public  boolean checkNumber(String input) {
    	try {
    		Long.parseLong(input);
    		return true;
    	} catch (Exception e) {
    		return false;
    	}
    	
    }
    public  ArrayList<PhoneM> refreshFavoriteByAoe() {
    	ArrayList<PhoneM> favItems = new ArrayList<PhoneM>();   
		try {
			
		   PhoneService.getInstance().getURL();
	    	 	
			Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,"starred=1",null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
	    	while (phones.moveToNext())
	    	{              				    		
	    		try {  
	    			PhoneM phoneM = new PhoneM();
	    			phoneM.setPhoneNum(phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
	    			PhoneM loadPhone = DB4CommandDao.getInstance().loadPhoneMByNum(phoneM.getPhoneNum(),((GlobalApplication)getApplication()).getDbPhone());
	    			if (loadPhone != null) {
	    				phoneM.setBrandName(loadPhone.getBrandName());
	    			}	
	    			phoneM.setName(phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)));
	    			favItems.add(phoneM);
	    		} catch (Exception e) {
	    			e.printStackTrace();
	    		}	
	    		        	
	    	}
	    	
        	/*AdapterTelListViewData adapterListViewData;
	        adapterListViewData = new AdapterTelListViewData(getBaseContext(),favItems,PhoneBrandConstant.MODECONTACT);	   	 		        
	        listV.setAdapter(adapterListViewData);
	        listV.invalidate();*/
	    	
	    	
		} catch (Exception e) {
			e.printStackTrace();
		}	
    	return favItems;
    } 
    public  void refreshFavorite() {
		try {
			
		   PhoneService.getInstance().getURL();
	    	ArrayList<PhoneM> favItems = new ArrayList<PhoneM>();    	
			Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,"starred=1",null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
	    	while (phones.moveToNext())
	    	{              				    		
	    		try {  
	    			PhoneM phoneM = new PhoneM();
	    			phoneM.setPhoneNum(phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
	    			PhoneM loadPhone = DB4CommandDao.getInstance().loadPhoneMByNum(phoneM.getPhoneNum(),((GlobalApplication)getApplication()).getDbPhone());
	    			if (loadPhone != null) {
	    				phoneM.setBrandName(loadPhone.getBrandName());
	    			}	
	    			phoneM.setName(phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)));
	    			favItems.add(phoneM);
	    		} catch (Exception e) {
	    			e.printStackTrace();
	    		}	
	    		        	
	    	}
	    	
        	AdapterTelListViewData adapterListViewData;
	        adapterListViewData = new AdapterTelListViewData(getBaseContext(),favItems,PhoneBrandConstant.MODECONTACT);	   	 		        
	        listV.setAdapter(adapterListViewData);
	        listV.invalidate();
	    	
	    	
		} catch (Exception e) {
			e.printStackTrace();
		}	
    	
    } 
    public ArrayList<PackageM>  refreshPackageDataByAoe() {
    	ArrayList<PackageM>  packages = new ArrayList<PackageM>();
    	try {
    		PackageM packageM1 =new PackageM();
    		packageM1.setBrandName("AIS");
    		packageM1.setName("โทรสะใจ");
    		packageM1.setDetail("อัตราค่าโทร 2.75 บาท โทรได้ 3 นาที");
    		
    		PackageM packageM2 =new PackageM();
    		packageM2.setBrandName("AIS");
    		packageM2.setName("โทรสุดคุ้ม");
    		packageM2.setDetail("โทรชั่วโมงละ 1 บาท ในเครือข่าย AIS ช่วงเวลา 23.00 น.-17.00 น. ส่วนเกินนาทีละ 1 บาท นอกช่วงเวลา/นอกเครือข่าย นาทีละ 1 บาท ค่าบริการสัปดาห์ละ 29 บาท " +
    				"โหลดเพลงฟรี! ไม่อั้นยกค่ายแกรมมี่ " +
    				" ฟรี!ค่าบริการรายเดือน Calling Melody 35 บาท" +
    				" ฟรี! ค่าบริการรายเดือนโหลดเพลงในค่ายแกรมมี่ ทั้ง Calling Melody ,Ring Tone ,Full Song และ Music Video 40 บาท (โดยกดผ่าน *123 โทรออก เสียค่าธรรมเนียมครั้งละ 5 บาท)" +
    				"• คิดอัตราค่าบริการเสริมในอัตราพิเศษ คือ SMS ข้อความละ 1 บาท ,MMS ข้อความละ 3 บาท และ GPRS นาทีละ 50 สตางค์" +
    				"(อัตราค่าบริการเสริม รวม VAT แล้ว) อัตราค่าบริการที่รวม VAT แล้ว โทรชั่วโมงละ 1.07 บาท ในเครือข่าย AIS ช่วงเวลา 23.00 น.-17.00 น." +
    				" ส่วนเกินนาทีละ 1.07 บาท นอกช่วงเวลา/นอกเครือข่าย นาทีละ 1.07 บาท โหลดเพลงฟรี! ไม่อั้นยกค่ายแกรมมี่ " +
    				"• การกดผ่าน *123 โทรออก เสียค่าธรรมเนียมครั้งละ 5.35 บาท/li> " +
    				"*หากไม่สามารถหักค่าบริการรายสัปดาห์ 29 บาท อัตราค่าโทรจะปรับเป็นนาทีละ 1.50 บาท" +
    				"ทุกเครือข่าย ตลอด 24 ช.ม. SMS ข้อความละ 2 บาท SMS ข้อความละ 6 บาท " +
    				"GPRS นาทีละ 1 บาท");
    		
    		PackageM packageM3 =new PackageM();
    		packageM3.setBrandName("DTAC");
    		packageM3.setName("โทรสะใจ2");
    		packageM3.setDetail("อัตราค่าโทร 2.75 บาท โทรได้ 3 นาที");
    		
    		packages.add(packageM1);
    		packages.add(packageM2);
    		packages.add(packageM3);
    		/*List<PhoneM>  phoneMs = dao.loadAllPhoneM(((GlobalApplication)getApplication()).getDbPhone());     
        	
        	if  (phoneMs != null) {        	
	        	for(PhoneM phoneM : phoneMs) { 
	        		listItems.add(phoneM);
	        	}
        	
        	}  */       	
        	                	        	        	    		
        	/*AdapterTelListViewData adapterListViewData;
	        adapterListViewData = new AdapterTelListViewData(getBaseContext(),listItems,PhoneBrandConstant.MODECONTACT);	   	 		        
	        listV.setAdapter(adapterListViewData);
	        listV.invalidate();*/
    	
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    	return packages;
    } 
    public ArrayList<PhoneM>  refreshContactDataByAoe() {
    	ArrayList<PhoneM>  listItems = new ArrayList<PhoneM>();
    	try {
    		
    		List<PhoneM>  phoneMs = dao.loadAllPhoneM(((GlobalApplication)getApplication()).getDbPhone());     
        	
        	if  (phoneMs != null) {        	
	        	for(PhoneM phoneM : phoneMs) { 
	        		listItems.add(phoneM);
	        	}
        	
        	}         	
        	                	        	        	    		
        	/*AdapterTelListViewData adapterListViewData;
	        adapterListViewData = new AdapterTelListViewData(getBaseContext(),listItems,PhoneBrandConstant.MODECONTACT);	   	 		        
	        listV.setAdapter(adapterListViewData);
	        listV.invalidate();*/
    	
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    	return listItems;
    } 
    public  void refreshContactData() {
    	try {
    		
        	List<PhoneM>  phoneMs = dao.loadAllPhoneM(((GlobalApplication)getApplication()).getDbPhone());     
        	ArrayList<PhoneM>  listItems = new ArrayList<PhoneM>();
        	if  (phoneMs != null) {        	
	        	for(PhoneM phoneM : phoneMs) { 
	        		listItems.add(phoneM);
	        	}
        	
        	}         	
        	                	        	        	    		
        	AdapterTelListViewData adapterListViewData;
	        adapterListViewData = new AdapterTelListViewData(getBaseContext(),listItems,PhoneBrandConstant.MODECONTACT);	   	 		        
	        listV.setAdapter(adapterListViewData);
	        listV.invalidate();
    	
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    	
    } 
    public ArrayList<PhoneM> filterContract(String c) {
    	ArrayList<PhoneM> result = new ArrayList<PhoneM>();
    	try {
	    	List<PhoneM>  phoneMs = dao.loadAllPhoneM(c,((GlobalApplication)getApplication()).getDbPhone());   
	    	/*
	    	for (PhoneM phoneM : phoneMs ) {
	    		if (phoneM.getName().toLowerCase().indexOf(c.toString().toLowerCase()) != -1) {
	    			result.add(phoneM);
	    		}
	    	}
	    	*/
	    	result.addAll(phoneMs);
    	} catch (Exception e ){
    		e.printStackTrace();
    	}	
    	
    	return  result;
    	
    }
    private   class LoaddataAsync extends AsyncTask<Integer, Void, ArrayList<PhoneM>> {
        /**
         * Compress and write the bitmap to disk on a separate thread.
         * @return TRUE if the write was successful, FALSE otherwise.
         */
    	private int mPosition;
    	private ListView mlistV;
    	private ProgressDialog mprogressDialog ;
    	 public LoaddataAsync(int position,ListView listV, ProgressDialog progressDialog) {
    	        mPosition = position;
    	        mlistV=listV;
    	        mprogressDialog=progressDialog;
    	  }
        @Override
        protected ArrayList<PhoneM> doInBackground(Integer... voids) { 
        	Log.d(LOG_TAG,"into doInBackground->"+voids+",->"+mPosition);
        	//mprogressDialog.show();
        	 ArrayList<PhoneM> aoe=  null;
        	 if(mPosition==1){
        		 aoe=refreshLogByAoe();
        		 Log.d(LOG_TAG,"into aoe size->"+aoe.size());
	    	}else if(mPosition==2){
	    		aoe=refreshFavoriteByAoe();
	    	}else if(mPosition==3){ 
	    		aoe=refreshContactDataByAoe();
	    	}/*else if(mPosition==4){
	    		aoe=refreshPackageDataByAoe();
	    	}*/
            return aoe;
        }

        @Override
		protected void onPostExecute(ArrayList<PhoneM> result) {
        	if(result!=null)
        		Log.d(LOG_TAG,"into onPostExecute size->"+result.size());
			// TODO Auto-generated method stub
        	 String mode=null;
        	 if(mPosition==1){
        		 mode=PhoneBrandConstant.MODELOG; 
	    	}else if(mPosition==2){
	    		 mode=PhoneBrandConstant.MODECONTACT; 
	    	}else if(mPosition==3){ 
	    		 mode=PhoneBrandConstant.MODECONTACT; 
	    	} 
        if( result!=null && mode!=null){
          AdapterTelListViewData adapterListViewData;
 	      adapterListViewData = new AdapterTelListViewData(getBaseContext(),result,mode);	   	 		        
 	      mlistV.setAdapter(adapterListViewData);
 	      mlistV.invalidate();
        }
        if(mprogressDialog!=null && mprogressDialog.isShowing())
        	mprogressDialog.hide();
		super.onPostExecute(result);
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}
    }
    private   class LoadPackageAsync extends AsyncTask<Integer, Void, ArrayList<PackageM>> {
        /**
         * Compress and write the bitmap to disk on a separate thread.
         * @return TRUE if the write was successful, FALSE otherwise.
         */
    //	private int mPosition;
    	private ListView mlistV;
    	private ProgressDialog mprogressDialog ;
    	 public LoadPackageAsync(ListView listV, ProgressDialog progressDialog) {
    	//        mPosition = position;
    	        mlistV=listV;
    	        mprogressDialog=progressDialog;
    	  }
        @Override
        protected ArrayList<PackageM> doInBackground(Integer... voids) { 
        	Log.d(LOG_TAG,"into LoadPackageAsync doInBackground->"+voids);
        	//mprogressDialog.show();
        	 return refreshPackageDataByAoe(); 
        }

        @Override
		protected void onPostExecute(ArrayList<PackageM> result) {
        	if(result!=null)
        		Log.d(LOG_TAG,"into onPostExecute size->"+result.size());
			// TODO Auto-generated method stub
          PackageAdapterView packageAdapterView;
          packageAdapterView = new PackageAdapterView(getBaseContext(),result);	   	 		        
 	      mlistV.setAdapter(packageAdapterView);
 	      mlistV.invalidate();
       
        if(mprogressDialog!=null && mprogressDialog.isShowing())
        	mprogressDialog.hide();
		super.onPostExecute(result);
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}
    }
}